// pages/mbrinfo/mbrinfo.js

//获取应用实例(获取app.js全局变量必须获取应用实例)
const App = getApp()

//网络请求封装
import Request_post from "../../../../request/Request_post"
import Request_get from "../../../../request/Request_get"

//系统设置项目:(请求地址-在封装中已经引入，这里不需要;   api调用的Appid-partner_app_id;   渠道ID-as_appid)
import config from '../../../../config/config'; 

//引入时间函数
var dateArray = require("../../../../utils/CustomFunction/getDayFirstNowLast.js")
var time = require("../../../../utils/CustomFunction/getNowTime.js")

//引入日期时间：（格式化、反格式化）函数
var formatDate = require("../../../../utils/CustomFunction/dateFormat.js")
var unformatDate = require("../../../../utils/CustomFunction/dateUnFormat.js")

var today = require("../../../../utils/CustomFunction//getToday.js")
var time = require("../../../../utils/CustomFunction/getNowTime.js")

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		switch_on_off:"",
		unbind_msg:{},
		mbr_info:{},
		name:"",
		sex:"",
		adr:"",
		oldPwd:"",
		newPwd:"",
		re_newPwd:"",

		bt_IsDisabled: false,
		bt_text: '确认提交',

		// 外链资源
		name_img:config.imageUrl+"name.png",
		question_img:config.imageUrl+"question.png",
		sex_img:config.imageUrl+"sex.png",
		brdcake_img:config.imageUrl+"brdcake.png",
		adr_img:config.imageUrl+"adr.png",

		// raido选项数组（作用1：利用此数组，渲染出raido选项框；作用2：利用数组的value值与api获取的sex值做比对，相等的则默认显示为选中状态；作用3：radio标签做双向数据绑定）
		sexObj: [ 
			{value: 'm', sexdes: '先生',checked: false}, 
			{value: 'f', sexdes: '女士',checked: false}
		],
		
		// 日期选择器定义的初始显示变量
		// birthday:"000000",
	},

	// 日期选择器绑定的方法
	bindbirthdayChange: function(e) {
		this.setData({
			birthday:e.detail.value
		})
		// console.log('当前日期的对应值',e.detail.value)
		// console.log("日期字符串截取："+this.data.birthday)
 	},

	// 实时获取输入框的值
	bindKeyInput: function (e) {
		var that = this
		that.setData({
			name: e.detail.value
		})
	},

	// 清除录入的信息
	deleteAll: function(){
		var that = this
		that.setData({name: ""})
	},


	// 获取用户信息
	getUserProfile(e) {
		var that = this
		// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
		wx.getUserProfile({
			desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: (res) => {
				console.log(res.userInfo)
				// https://developers.weixin.qq.com/community/develop/doc/000cacfa20ce88df04cb468bc52801 官方文档，不再支持获取性别
				// if(res.userInfo.gender == 1){
				// 	that.setData({
				// 		sexObj: [ 
				// 			{value: 'm', sexdes: '先生',checked: true}, 
				// 			{value: 'f', sexdes: '女士',checked: false}
				// 		],
				// 		sex:'m'
				// 	})
				// }else{
				// 	that.setData({
				// 		sexObj: [ 
				// 			{value: 'm', sexdes: '先生',checked: false}, 
				// 			{value: 'f', sexdes: '女士',checked: true}
				// 		],
				// 		sex:'f'
				// 	})
				// }
				that.setData({
					name: res.userInfo.nickName
				})
			}
		})
	},

	// radio选项框绑定的方法
	radioChange(e) {
  // console.log('radio发生change事件，携带value值为：', e.detail.value)
    const sexObj = this.data.sexObj
    for (var i = 0; i < sexObj.length ; ++i) {
      sexObj[i].checked = sexObj[i].value === e.detail.value
    }
    this.setData({
			sex:e.detail.value
		})
  },

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		var that = this
		const dd = formatDate.DateFormat(config.birthday) 
		that.setData({birthday:dd})
		// console.log(that.data.birthday)
		// console.log(App.globalData.wx_openid)
	},


	
	/**
	 * 确认修改 SubmitEnter事件（1：更新资料）
	 */
	SubmitEnter:function(){
		var that = this 
		// 点击按钮后，先禁用按钮
		that.setData({bt_IsDisabled: true,bt_text:'正在提交'})

		that.setData({
			bdt:that.data.birthday.substring(0,4)+that.data.birthday.substring(5,7)+that.data.birthday.substring(8,10), //格式化日期变量  将 yyyy-mm-dd 转为  yyyymmdd
			name:that.data.name.trim()
		})
		if( 
			that.data.name == "" || 
			that.data.name == undefined || 
			that.data.name == "undefined" || 
			that.data.name == config.name || 
			that.data.bdt == config.birthday || 
			that.data.bdt == "0000-00-00" || 
			that.data.sex == config.sex)
			{
				wx.showModal({
					title:"尊敬的会员",
					content:"请您完整的填写个人信息\n\n“姓名、性别、生日”为必填项\n\n请填写完整信息再提交。",
					showCancel:false
				})
				that.setData({bt_IsDisabled: false,bt_text: '确认提交',})
				return;
			}

		//Api请求：B02-会员注册接口
		Request_post.post(
			config.domainName+"api_wxmkt_server/mbrreg/registerwxmbr", 
			{
				cltid: config.cltid,
				name: that.data.name,
				sex: that.data.sex,
				birthday: that.data.bdt,
				adr: that.data.adr,
				crtno: "",
				pltno: "",
				mbrclsid: "01",
				cardclsid: "01"
			},
			function(res){
				console.log(res)
				if(res && res.return_no == 1){   //会员注册成功
					//将会员信息存入缓存
					wx.setStorageSync('StrMbrInfo', res.return_data )
					// 调用积分增加规则的查询方法（积分增加规则方法中 调用 增加积分的方法）
					that.findmbritgruladd();
					that.regadditgPromise.then(v => { 
						that.setData({
							mbrregflg: that.data.newmbritgflg,
							mbrregItg: that.data.addItg
						})
						App.globalData.regflg = 'y'
						that.wx_redirectTo();
					})
				}else{
					wx.showModal({
						title:res?res.return_msg:'会员资料更新Api调用失败！',
						showCancel: false,		//是否显示取消按钮
						confirmText:"是",		//默认是“确定”
						confirmColor: 'skyblue',	//确定文字的颜色
						success: function (res) {
							if (res.confirm) {		//点击确认
								that.setData({
									bt_IsDisabled: false,
									bt_text: '确认提交'
								})
							}
						}
					})
				}
			}
		)
	},


	// 跳转的页面
	wx_redirectTo:function(){
		var that = this
		if(App.globalData.Scenepath === '/pages/index/index'){
			wx.redirectTo({
				url:App.globalData.homePage + "?mbrregflg="+that.data.mbrregflg+"&mbrregItg="+that.data.mbrregItg
			});
		}else if(App.globalData.Scenepath !== '/pages/index/index'){
			wx.redirectTo({
				url:App.globalData.Scenepath+App.globalData.Scenepath_parameter + "?mbrregflg="+that.data.mbrregflg+"&mbrregItg="+that.data.mbrregItg
			});
		}
	 },
 

	/** Api请求  001-会员赚积分活动规则查询 —— 被调用*/
	findmbritgruladd:function(){
		var that = this
		this.setData({
			newmbritgflg: "n",
			addItg: 0,
			Today:unformatDate.DatString(today.getToday()),
			getTodayDtm: unformatDate.DatString(today.getToday()) + unformatDate.DatString(time.getNowTime()) 
		})
		// Api请求：06-001 会员赚积分活动规则查询
		that.regadditgPromise = new Promise ((resolve,reject) => {
			Request_get.get(
				config.domainName+'api_wxmkt_server/mbritgadd/findmbritgruladd',
				{
					additgactid:'01' //赚积分活动规则ID（01-新会员注册送积分、02-完善会员资料奖励积分、03-签到送积分）
				},
				function(res){
					const additgList = res.return_data
					if(additgList.length > 0){
						for(var i in additgList){
							if(  //长期规则
								additgList[i].rulclsid == '01' && additgList[i].itgvlu > 0 &&  additgList[i].enldat <= that.data.getTodayDtm && additgList[i].disdat >= that.data.getTodayDtm){
								var longRuladdItg = additgList[i].itgvlu
								// console.log(longRuladdItg)
							}else if(  //临时规则
								additgList[i].rulclsid == '02' && additgList[i].itgvlu > 0 && additgList[i].enldat <= that.data.getTodayDtm && additgList[i].disdat >= that.data.getTodayDtm){
								var shortRuladdItg  = additgList[i].itgvlu
								// console.log(shortRuladdItg)
							}
						}
						// 临时规则 和 长期规则 的最终赋值（临时规则存在，则积分值为临时规则的积分值，否则为长期规则的积分值）
						shortRuladdItg? that.setData({newmbritgflg:"y",addItg:shortRuladdItg}): that.setData({newmbritgflg:"y",addItg:longRuladdItg})
						// 调用增加积分方法
						that.newMbrregitgadd();
						resolve(true);
					}else{
						that.setData({newmbritgflg:"n",addItg:0})
						resolve(true);
					}
			})
		})
	},


	/** Api请求  06-002:会员积分增加 —— 被06-001调用*/
	newMbrregitgadd:function(){
		var that = this
		that.setData({
			bllno: Math.round(new Date() / 1000),
		})
		Request_post.post(
			config.domainName+"api_wxmkt_server/mbritgadd/addmbritg",
			{
				oprcltid: "001",
				oprid: "51",
				oprdat: that.data.getTodayDtm,     
				srcbllno: that.data.bllno,
				additgvlu: that.data.addItg,
				brief: "新会员注册送积分"
			},
			function(res){
				if(res && res.return_no == 1){
					that.setData({
						itgaddflg: '01',
						msg: res.return_msg
					})
				}
			}
		)
	},








 

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
	
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},
	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	},
	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

})
